
import { window,extensions,env,workspace } from 'vscode';
import * as nls from 'vscode-nls';
import {GitExtension} from '../api/git';

//load i18n
const localize = nls.loadMessageBundle();
//load git api
const gitExtension = extensions.getExtension<GitExtension>('vscode.git')?.exports;
const git = gitExtension?.getAPI(1);

export function lineShare() {

	let activeTextEdit=window.activeTextEditor;
	if (activeTextEdit){
		// get workspace
		let folder=workspace?.getWorkspaceFolder(activeTextEdit.document.uri);
		if (folder){
			// get repository
			let defaultRepository=git?.getRepository(folder.uri);
			if(defaultRepository){
				let defaultRemote=defaultRepository.state.remotes[0];
				if(defaultRemote){
					//https://github.com/microsoft/vscode/blob/1091af7d655335d07cb500b38f1270cf14743049/src/vs/workbench/browser/parts/editor/editorStatus.ts#L842
					//获取当前行号
					let line=1+window.activeTextEditor?.selection.active.line!;
					if (isNaN(line)){
						window.showErrorMessage(localize('error.isNotFile','Active edit is not File, Can\'t get the current line'));
					}else{
						//TODO 检查当前文件是否是文件管理文件
						let currentPath=activeTextEdit.document.uri.fsPath;
						if (currentPath.startsWith(defaultRepository.rootUri.fsPath)){
							let url=`${defaultRemote.fetchUrl?.replace('.git','')}/blob/${defaultRepository.state.HEAD?.commit}${currentPath.replace(defaultRepository.rootUri.fsPath,'').replace(/\\/g,'/')}#L${line}`;
							env.clipboard.writeText(url);
							window.showInformationMessage(localize('info.writeClipboard',"{0} is write to clipboard",url));
						}else{
							window.showErrorMessage(localize('error.fileNotInProject','current file not in Project!'));
						}
					}
				}else{
					window.showErrorMessage(localize('error.notHasRemote','current repository not has remote!'));
				}
			}else{
				window.showErrorMessage(localize('error.notHasRepository','current file not has Repository!'));
			}
		}else{
			window.showErrorMessage(localize('error.notInWorkspaceFolder','current file not in Workspace!'));
		}
	}else{
		window.showErrorMessage(localize('error.notActiveFile','can\'t find active File!'));
	}


}